package com.openthinks.carPeccancy.rest;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.openthinks.carPeccancy.bean.PeccancyRecords;
import com.openthinks.carPeccancy.comm.ParamsMap;
import com.openthinks.carPeccancy.utils.HttpUtils;

@Controller
public class CarPeccancyREST {
    public CarPeccancyREST(){}  
    
    @RequestMapping(value="/index/{user}", method=RequestMethod.GET)  
    public ModelAndView demo(HttpServletRequest request, HttpServletResponse response,  
            @PathVariable("user") String user, ModelMap modelMap) throws Exception{  
        modelMap.put("user", user);
        return new ModelAndView("/index", modelMap);  
    }  
      
    @RequestMapping(value="/welcome", method=RequestMethod.GET)  
    public String welcome(){  
        return "/welcome";   
    }  

    @SuppressWarnings("unchecked")
    @RequestMapping(value="/peccancyRecords", method=RequestMethod.GET)
    @ResponseBody
    public Map<String,List<PeccancyRecords>> peccancyRecords(HttpServletRequest request, HttpServletResponse response){
        Map<String,List<PeccancyRecords>> peccancyRecordsResult = new HashMap<String,List<PeccancyRecords>>();
        
        try {
            //发送查询请求
            String result = new HttpUtils().get("http://www.c580.net/QueryIndex.aspx", new ParamsMap<String, String>()
                    .add("provinceid", "44")
                    .add("cityid", "4403")
                    .add("carnumber", "粤B0033H")
                    .add("carcode", "1776")
                    .add("cardrivenumber", "")
                    .add("sign", ""), 60, "gb2312");
            
            SAXReader reader = new SAXReader();
            reader.getDocumentFactory().setXPathNamespaceURIs(
                    new ParamsMap<String, String>()
                            .add("vqns", "http://sogrand.cn/query"));
            Document doc = reader.read(new StringReader(result));
            Element rootElement = doc.getRootElement();
            
            if ("0".equals(rootElement.elementText("ErrorCode"))) {
                if ("true".equals(rootElement.elementText("HasData"))) {
                    List<PeccancyRecords> peccancyRecordsList = new ArrayList<PeccancyRecords>();
                    
                    Date nowDate = new Date();
                    
                    List<Element> violiationRecords = (List<Element>) doc.selectNodes("/QueryResult/vqns:Records/vqns:VioliationRecord");
                    for (Element violiationRecord : violiationRecords) {
                        String time = violiationRecord.elementTextTrim("Time");
                        if (StringUtils.isNotEmpty(time)) {
                            time = time.replaceAll("&nbsp;", " ").replaceAll("&gt;", ">").replaceAll("&lt;", "<")
                                    .replaceAll("&quot;", "\"").trim().replace(".0", "");
                        }
                        String location = violiationRecord.elementTextTrim("Location");
                        if (StringUtils.isNotEmpty(location)) {
                            location = location.replaceAll("&nbsp;", " ").replaceAll("&gt;", ">").replaceAll("&lt;", "<")
                                        .replaceAll("&quot;", "\"");   
                        }
                        String reason = violiationRecord.elementTextTrim("Reason");
                        if (StringUtils.isNotEmpty(reason)) {
                            reason = reason.replaceAll("&nbsp;", " ").replaceAll("&gt;", ">")
                                      .replaceAll("&lt;", "<").replaceAll("&quot;", "\"");
                        }
                        
                        if(StringUtils.isNotEmpty(time)||StringUtils.isNotEmpty(location)||StringUtils.isNotEmpty(reason)){
                            //保存违章记录
                            PeccancyRecords peccancyRecords = new PeccancyRecords();
                            peccancyRecords.setDateTime(time);
                            peccancyRecords.setLocation(location);
                            peccancyRecords.setDescription(reason);
                            peccancyRecords.setLatestQueryDate(nowDate);
                            
                            peccancyRecordsList.add(peccancyRecords);
                        }
                    }
                    peccancyRecordsResult.put("粤B0033H", peccancyRecordsList);
                } 
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        return peccancyRecordsResult;
    }
}
